<?php

namespace app\controllers;

use app\models\Project;
use app\models\User;
use Yii;
use yii\db\Query;
use yii\filters\AccessControl;
use yii\helpers\VarDumper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;


class SiteController extends Controller
{
    public $enableCsrfValidation = false;
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout','index','index1','index2','index3'],
                'rules' => [
                    [
                        'actions' => ['logout','index','index1','index2','index3','change-mine-password'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'actions' => ['login'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post','get'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        $this->layout = false;
        return $this->render('index');
    }

    public function actionIndex1()
    {
        $asterisk_db = Yii::$app->get('asterisk_db');
        $callcenter_db = Yii::$app->get('callcenter_db');
        //分机数
        $count_exten = (new Query())->from('users')->count('*',$asterisk_db);
        //中继数
        $count_trunk = (new Query())->from('trunks')->count('*',$asterisk_db);
        //队列数
        $count_queue = (new Query())->from('queues_config')->count('*',$asterisk_db);
        //呼出任务数
        $count_campaign = (new Query())->from('campaign')->count('*',$callcenter_db);

        //批量呼出任务情况
        $campaign = (new Query())->from('campaign')->orderBy('id desc')->limit(2)->all($callcenter_db);
        foreach ($campaign as &$p){
            //总呼叫数
            $p['total'] = (new Query())->from('calls')->where(['id_campaign'=>$p['id']])->count('id',$callcenter_db);
            //完成呼叫数
            $p['abandoned'] = (new Query())->from('calls')->where(['id_campaign'=>$p['id'],'status'=>'Abandoned'])->count('id',$callcenter_db);
            //进度
            $hascall = (new Query())->from('calls')->where(['and','id_campaign='.$p['id'],'status is not null'])->count('id',$callcenter_db);
            $p['progress'] = $p['total']>0?100*round($hascall/$p['total'],4).'%':'0%';
            //接通率
            $p['percent'] = $hascall>0?100*round($p['abandoned']/$hascall,4).'%':'0%';
        }

        //线形图表统计(一个星期内的时间区间)
        $line_data = [];
        for ($n=-3;$n<=3;$n++){
            $start = mktime(0,0,0,date('m'),date('d')+$n,date('Y'));
            $end = mktime(0,0,0,date('m'),date('d')+$n+1,date('Y'));
            $line_data[$start] = Project::find()->where(['between','created_at',$start,$end])->count();
        }
        $line_data_x = array_map(function ($v){
            return "'".date('m-d',$v)."'";
        },array_keys($line_data));

        $line_data_x = implode(',',$line_data_x);
        $line_data_y = implode(',',array_values($line_data));

        return $this->render('index1',[
            'count_exten'=>$count_exten,
            'count_trunk'=>$count_trunk,
            'count_queue'=>$count_queue,
            'count_campaign'=>$count_campaign,
            'campaign'=>$campaign,
            'line_data_x'=>$line_data_x,
            'line_data_y'=>$line_data_y,
        ]);
    }

    public function actionIndex2()
    {
        return $this->render('index2');
    }

    public function actionIndex3()
    {
        return $this->render('index3');
    }

    /**
     * Login action.
     *
     * @return Response|string
     */
    public function actionLogin()
    {
        $this->layout = false;
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }

        $model->password = '';
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    /**
     * Logout action.
     *
     * @return Response
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionChangeMinePassword()
    {
        $model = User::findOne(Yii::$app->user->id);
        if ($model===null){
            throw new NotFoundHttpException('用户不存在');
        }
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'change-mine-password';
            if ($model->load($data,'')&&$model->changeMinePassword()){
                Yii::$app->session->setFlash('info','密码更新成功');
                return $this->refresh();
            }
        }
        return $this->render('change-mine-password',['model'=>$model]);
    }

}
